<?php

defined('SYSPATH') or die('No direct access allowed.');

class Controller_User extends Controller_Site {

    function action_profile() {
        $id = $this->request->param();
        $user = ORM::factory('user')->where('name', '=', $id)->find();
        $this->content->set('user', $user);
    }

    function action_login() {
        if ($this->request->method() == 'POST') {
            $user = ORM::factory('user')->where('name', '=', $this->request->post('username'))->find();
            Session::instance()->set('username', $user->name);
            Session::instance()->set('user_id', $user->id);
            Session::instance()->set('role_id', $user->role_id);
            $this->request->redirect('/');
        }
    }

    function action_logout() {
        Session::instance()->destroy();
        $this->request->redirect('/');
    }

    function action_registration() {
        if ($this->request->method() == 'POST') {
            $i = 0;
            if ($this->request->post('username') == '') {
                $i++;
                $error[$i] = 'Hiányzó felhasználónév';
            }
            if ($this->request->post('password') == '') {
                $i++;
                $error[$i] = 'Hiányzó jelszó';
            }
            if ($this->request->post('email') == '') {
                $i++;
                $error[$i] = 'Hiányzó email cím';
            }
            if ($this->request->post('password') != $this->request->post('password2')) {
                $i++;
                $error[$i] = 'Nem egyező jelszavak';
            }

            $name = DB::select()->from('user')->where(DB::expr('LOWER(name)'), '=', strtolower($this->request->post('username')))->execute();
            if ($name->count() > 0) {
                $i++;
                $error[$i] = 'Létező felhasználónév';
            }
            $email = ORM::factory('user')->where('email', '=', strtolower($this->request->post('email')))->find();
            if ($email->loaded()) {
                $i++;
                $error[$i] = 'Létező email cím';
            }

            if ($i == 0) {
                $user = ORM::factory('user');
                $user->name = $this->request->post('username');
                $user->email = strtolower($this->request->post('email'));
                $user->password = sha1($this->request->post('password'));
                $user->role_id = 1;
                $user->save();
            }

            if (isset($error)) {
                $this->content->set('error', $error);
            } else {
                Session::instance()->set('username', $user->name);
                Session::instance()->set('user_id', $user->id);
                Session::instance()->set('role_id', $user->role_id);
                $this->request->redirect('/');
            }
        }
    }

}

